package com.ling.rocketmq.producer;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class RocketmqProducerFactory<T> implements FactoryBean<T>, ApplicationContextAware {

    private Class<T> interfaceClass;
    private ApplicationContext applicationContext;
    private final RocketmqProducerProxy producerProxy;

    public RocketmqProducerFactory(Class<T> interfaceClass) {
        this.interfaceClass = interfaceClass;
        producerProxy = new RocketmqProducerProxy(interfaceClass);
    }

    @Override
    public T getObject() throws Exception {
        return (T) producerProxy
                .setProducerFactory(applicationContext.getBean(MQProducerFactory.class))
                .getProxy();
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }

    @Override
    public boolean isSingleton() {
        // 单例模式
        return true;
    }

    public Class<T> getInterfaceClass() {
        return interfaceClass;
    }

    public void setInterfaceClass(Class<T> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}